#pragma executation_character_set("utf-8") // 源文件中的字符串字面量应该以UTF-8编码处理。
#include "qmyimagebutton.h"
#include<QPainter>
#include<QDebug>
#include<QPushButton>
#include<QImage>

QMyImageButton::QMyImageButton(QWidget *parent)
    : QWidget{parent}
{
    isChecked = false;

    buttonStyle = ButtonStyle::ButtonStyle_2;

    strImgOffFile = ":/image/btncheckoff2.png";

    strImgOnFile = ":/image/btncheckon2.png";

    strImgFile = strImgOffFile;

}

void QMyImageButton::mousePressEvent(QMouseEvent *event)
{
    strImgFile = isChecked?strImgOffFile:strImgOnFile;
    isChecked = !isChecked;
    emit checkedChangeed(isChecked);
    this->update();
}

void QMyImageButton::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHints(QPainter::SmoothPixmapTransform);
    QImage Image(strImgFile);
    Image = Image.scaled(this->size(),Qt::KeepAspectRatio, Qt::SmoothTransformation);

    // 按照比例自动居中制作
    int nPixX = rect().center().rx() - Image.width()/2;
    int nPixY = rect().center().ry() - Image.height()/2;
    QPoint point(nPixX,nPixY);
    painter.drawImage(point,Image);
}

bool QMyImageButton::getChecked() const
{
    return isChecked;
}

QMyImageButton::ButtonStyle QMyImageButton::getButtonStyle() const
{
    return this->buttonStyle;
}

QSize QMyImageButton::sizeHint() const
{
    return QSize(87,28);
}

QSize QMyImageButton::minimumSizeHint() const
{
    return QSize(87,28);
}

void QMyImageButton::setChecked(bool isChecked)
{
    if(this->isChecked != isChecked)
    {
        this->isChecked = isChecked;
        strImgFile = isChecked?strImgOnFile:strImgOffFile;
        this->update();
    }
}

void QMyImageButton::setButtonStyle(const ButtonStyle &buttonstyle)
{
    if(this->buttonStyle != buttonstyle)
    {
        this->buttonStyle = buttonstyle;
        switch(buttonstyle)
        {
        case ButtonStyle_1:
        {
            strImgOffFile = ":/image/btncheckoff1.png";
            strImgOnFile = ":/image/btncheckon1.png";
            this->resize(87,28);
        }
        break;
        case ButtonStyle_2:
        {
            strImgOffFile = ":/image/btncheckoff2.png";
            strImgOnFile = ":/image/btncheckon2.png";
            this->resize(87,28);
        }
        break;
        case ButtonStyle_3:
        {
            strImgOffFile = ":/image/btncheckoff3.png";
            strImgOnFile = ":/image/btncheckon3.png";
            this->resize(96,38);
        }
        break;
        }

        strImgFile = isChecked?strImgOnFile:strImgOffFile;
        setChecked(isChecked);
        this->update();
        updateGeometry();

    }
}


